﻿using AutoDeployForSims.Common;
using AutoDeployForSims.Entity;
using AutoDeployForSims.Model;
using AutoDeployForSims.Utility;
using AutoDeployForSims.ViewModel;
using MyUtility.Utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;

namespace AutoDeployForSims.Service
{
    public class GetConfigService
    {
        #region 常量
        private string RootPath = AppDomain.CurrentDomain.BaseDirectory;
        private List<string> cBITypes = new List<string> { "北方交大", "卡斯柯", "设计院", "铁科院", "SDM", "东方宇业" };
        private Dictionary<string, string> ModuleNamePairs = new Dictionary<string, string> { 
            {"1", "移频发送综合板" },
            {"2", "移频接收综合板" },
            {"3", "电缆侧电压板" },
            {"4", "移频接收采集板" },
            {"5", "道岔表示电压采集板" },
            {"6", "25Hz轨道电路电压、相位采集板" },
            {"7", "50Hz交流轨道电压采集板" },
            {"8", "50Hz直流轨道电压采集板" },
            {"9", "48路模入板" },
            {"10", "48路开关量板" },
            {"15", "防雷分线柜信号机采集模块" },
            {"16", "TC6YZⅡ-J移频综合采集器" },
            {"17", "TC6V2FJ-DMH电码化电压采集传感器" },
            {"18", "TC6V2FⅡ-J区间接收综合采集传感器" },
            {"19", "TC6V2F-J区间接收综合采集传感器" },
            {"20", "交流道岔表示模块" },
            {"21", "直流道岔表示模块" },
            {"22", "25HZ轨道测试盒" },
            {"23", "8路25Hz轨道电流监测模块" },
            {"24", "8路道岔电流监测模块" },
            {"25", "区间监测采集模块" },
            {"26", "维博高频外电网监测模块" },
            {"27", "25Hz轨道电压相位采集盒带50Hz干扰" },
            {"28", "温度湿度采集模块" },
            {"30", "维博直流道岔电流模块" },
            {"31", "铁大直流道岔电流模块" },
            {"32", "维博交流道岔电流模块" },
            {"33", "外电网模块" },
            {"34", "CAN透传模块" },
            {"35", "站联模块" },
            {"36", "半自闭模块" },
            {"37", "断相保护器&交流连续式轨道电路发送采集模块" },
            {"38", "交流连续式轨道电路接收采集模块" },
            {"40", "电码化接收电压采集模块" },
            {"41", "TC6300-03(带谐波)" },
            {"42", "25Hz轨道电路发送电压传感器" },
            {"43", "灯丝电流传感器" },
            {"46", "25Hz轨道电路接受电压传感器" },
            {"50", "信号机采集模块" },
            {"51", "25HZ轨道接收" },
            {"52", "道岔表示电压模块" },
            {"53", "25HZ轨道发送" },
            {"54", "6线3对模块采样场联站联" },
            {"55", "交流道岔曲线加表示电压" },
            {"56", "4线直流道岔加表示电压" },
            {"57", "6线直流道岔加表示电压" }
        }; 

        private string SourceSimuToolsPath = @"D:\#模拟工具目录";//指定目录，后续考虑从ftp上直接拷贝
        private string TargetSimuToolsFolder = AppDomain.CurrentDomain.BaseDirectory + @"SimulatonTools";
        private string ScriptServerPort = "6789";
        #endregion
        private CfgType cfgType;
        private string dbm;
        private string LocalIP;
        private string TargetSimuToolsPath;
        private Dictionary<string, List<string>> AnalogkeyValuePairs = new Dictionary<string, List<string>>();
        private Dictionary<string, List<string>> InterfacekeyValuePairs = new Dictionary<string, List<string>>();

        public GetConfigService()
        {
            //获得本机IP
            LocalIP = GetLocalIP();
        }

        private string GetLocalIP()
        {
            string localIP = "127.0.0.1";
            try
            {
                // 获取本机主机名
                string hostName = Dns.GetHostName();

                // 使用主机名获取IPHostEntry
                IPHostEntry ipEntry = Dns.GetHostEntry(hostName);

                // 输出所有与主机名关联的IPV4地址
                Console.WriteLine($"本机({hostName})的IP地址:");
                foreach (IPAddress ip in ipEntry.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork) // 只输出IPv4地址
                    {
                        localIP = ip.ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取IP地址时发生错误: {ex.Message}");
            }
            return localIP;
        }

        public bool ReadAPPStartPathConfig(ref List<AppStatusEntity> appStatusEntities)
        {
            appStatusEntities.Clear();
            bool isRight = false;
            //判断是否存在配置文件
            string fileConfigPath = RootPath + "\\CFG\\APPStartPathConfig.ini";
            if (File.Exists(fileConfigPath))
            {
                string sum = INIHelper.Read("基本参数", "总数", "-1", fileConfigPath);
                for (int i = 0; i < int.Parse(sum); i++)
                {
                    int num = i + 1;
                    string name = INIHelper.Read("对象信息" + num.ToString(), "名称", "-1", fileConfigPath);
                    string path = INIHelper.Read("对象信息" + num.ToString(), "启动位置", "-1", fileConfigPath);
                    string appName = Path.GetFileNameWithoutExtension(path);
                    AppStatusEntity appStatusEntity = new AppStatusEntity(name, appName, path);
                    appStatusEntities.Add(appStatusEntity);
                }
                isRight = true;
            }
            return isRight;
        }
        public bool WriteNewAPPStartPathConfigFile(ObservableCollection<SimuToolInfoEntity> SimuToolInfoList)
        {
            bool isRight = false;
            string fileConfigPath = RootPath + "\\CFG\\NewAPPStartPathConfig.ini";
            if (File.Exists(fileConfigPath))
            {                
                File.Delete(fileConfigPath);                
            }
            // 获取当前系统的默认ANSI编码
            Encoding ansiEncoding = Encoding.Default;
            // 使用ANSI编码创建并写入文件
            using (FileStream fs = new FileStream(fileConfigPath, FileMode.Create, FileAccess.Write))
            using (StreamWriter writer = new StreamWriter(fs, ansiEncoding))
            {                
                //得到需要配置的列表
                List<SimuToolInfoEntity> simuToolInfoList = new List<SimuToolInfoEntity>();
                foreach (SimuToolInfoEntity SimuToolInfo in SimuToolInfoList)
                {
                    if (SimuToolInfo.IsNeed)
                    {
                        simuToolInfoList.Add(SimuToolInfo);
                    }
                }
                writer.WriteLine($"[{"基本参数"}]");
                writer.WriteLine($"{"总数"}={simuToolInfoList.Count().ToString()}");

                int num = 0;
                foreach (SimuToolInfoEntity simuToolInfo in simuToolInfoList)
                {
                    num++;
                    string section = "对象信息" + num.ToString();
                    writer.WriteLine($"[{section}]");
                    writer.WriteLine($"{"名称"}={simuToolInfo.SimuToolName}");
                    writer.WriteLine($"{"启动位置"}={simuToolInfo.SimuAPPPath}");                   
                }
                isRight = true;
            }
            return isRight;
        }
        public bool ReadNewAPPStartPathConfig(ref List<AppStatusEntity> newAppStatusEntities)
        {
            newAppStatusEntities.Clear();
            bool isRight = false;
            //判断是否存在配置文件
            string fileConfigPath = RootPath + @"CFG\NewAPPStartPathConfig.ini";
            if (File.Exists(fileConfigPath))
            {
                string sum = INIHelper.Read("基本参数", "总数", "-1", fileConfigPath);
                for (int i = 0; i < int.Parse(sum); i++)
                {
                    int num = i + 1;
                    string name = INIHelper.Read("对象信息" + num.ToString(), "名称", "-1", fileConfigPath);
                    string path = INIHelper.Read("对象信息" + num.ToString(), "启动位置", "-1", fileConfigPath);
                    string appName = Path.GetFileNameWithoutExtension(path);
                    AppStatusEntity appStatusEntity = new AppStatusEntity(name, appName, path);
                    newAppStatusEntities.Add(appStatusEntity);
                }
                isRight = true;
            }
            return isRight;
        }

        public CfgType ReadConfig()
        {
            //得到模拟工具目标路径
            dbm = Path.GetFileName(GlobalVari.CFGPath);
            TargetSimuToolsPath = Path.Combine(TargetSimuToolsFolder, dbm + "模拟工具");

            //CfgType cfgType;
            //判断是否存在配置文件
            string fileConfigPath = GlobalVari.CFGPath + "\\analogExtend.ini";
            if (File.Exists(fileConfigPath))
            {
                cfgType = CfgType.CSM_TD_20;
                //读Interface.ini
                ReadInterfaceConfig();
            }
            else
            {
                cfgType = CfgType.CSM_TD_10;
            }
            return cfgType;
        }

        private void ReadInterfaceConfig()
        {            
            string fileConfigPath = GlobalVari.CFGPath + "\\Interface.ini";
            if (File.Exists(fileConfigPath))
            {
                InterfacekeyValuePairs.Clear();
                string number = INIHelper.Read("外部通信接口", "接口总数", "-1", fileConfigPath);
                for (int i = 0; i < int.Parse(number); i++)
                {
                    string section = "通信配置_" + (i + 1).ToString();
                    string type = INIHelper.Read(section, "配置类型", "-1", fileConfigPath);
                    
                    if (InterfacekeyValuePairs.TryGetValue(type, out List<string> sectionsTemp))
                    {
                        sectionsTemp.Add(section);
                    }
                    else
                    {
                        List<string> sections = new List<string>();
                        sections.Add(section);
                        InterfacekeyValuePairs.Add(type, sections);
                    }
                }
            }
        }

        public bool ReadFrankConfig(ref List<FrankCFGInfoEntity> frankCFGInfoEntities)
        {
            bool isRight = false;
            //判断是否存在配置文件
            string fileConfigPath = GlobalVari.CFGPath + "\\FrankCFG.ini";
            if (File.Exists(fileConfigPath))
            {
                int canPort = 56870;//CAN接口模拟器端口号从56871开始
                int port1 = 19;
                int port2 = 20;//com21-com22开始为自采集串口对
                frankCFGInfoEntities = new List<FrankCFGInfoEntity>();
                string number = INIHelper.Read("总配置", "通信板数量", "-1", fileConfigPath);
                for (int i = 0; i < int.Parse(number); i++)
                {
                    canPort++;
                    string key = "通信板" + (i + 1).ToString();
                    FrankCFGInfoEntity frankCFGInfoEntity = new FrankCFGInfoEntity();
                    frankCFGInfoEntity.CommInfoEntities.Clear();
                    frankCFGInfoEntity.Title = key;
                    string ip1 = INIHelper.Read(key, "通信IP地址第一位", "-1", fileConfigPath);
                    string ip2 = INIHelper.Read(key, "通信IP地址第二位", "-1", fileConfigPath);
                    string ip3 = INIHelper.Read(key, "通信IP地址第三位", "-1", fileConfigPath);
                    string ip4 = INIHelper.Read(key, "通信IP地址第四位", "-1", fileConfigPath);
                    if (ip1.Contains("；"))
                    {
                        ip1 = ip1.Replace("；", "");
                    }
                    if (ip2.Contains("；"))
                    {
                        ip2 = ip2.Replace("；", "");
                    }
                    if (ip3.Contains("；"))
                    {
                        ip3 = ip3.Replace("；", "");
                    }
                    if (ip4.Contains("；"))
                    {
                        ip4 = ip4.Replace("；", "");
                    }
                    frankCFGInfoEntity.CommIP = ip1 + "." + ip2 + "." + ip3 + "." + ip4;
                    frankCFGInfoEntity.CANPort = canPort.ToString();
                    string portNum = INIHelper.Read("通信板" + (i + 1).ToString(), "端口数量", "-1", fileConfigPath);
                    if (portNum.Contains("；"))
                    {
                        portNum = portNum.Replace("；", "");
                    }
                    for (int j = 0; j < int.Parse(portNum); j++)
                    {
                        string key2 = "通信板" + (i + 1).ToString() + "端口" + (j + 1).ToString();
                        CommInfoEntity commInfo = new CommInfoEntity();
                        commInfo.PortType = INIHelper.Read(key, "端口类型" + (j + 1).ToString(), "-1", fileConfigPath);
                        if (commInfo.PortType == "4" || commInfo.PortType == "5")
                        {
                            if (commInfo.PortType == "4")
                            {
                                port1 += 2;
                                port2 += 2;
                                commInfo.CommBoardPortNumber = "COM" + port1.ToString();
                                commInfo.SimuToolPortNumber = "COM" + port2.ToString();
                            }
                            
                            commInfo.PortNumber = INIHelper.Read(key2, "端口号", "-1", fileConfigPath);
                            commInfo.BaudRate = INIHelper.Read(key2, "波特率", "-1", fileConfigPath);
                            commInfo.MoudleNumber = INIHelper.Read(key2, "模块数量", "-1", fileConfigPath);
                            string MoudleAddress = INIHelper.Read(key2, "模块地址", "-1", fileConfigPath);
                            string MoudleType = INIHelper.Read(key2, "模块类型", "-1", fileConfigPath);
                            commInfo.MoudleId = INIHelper.Read(key2, "分机号", "-1", fileConfigPath);
                            commInfo.MainProtocol = INIHelper.Read(key2, "主协议号", "-1", fileConfigPath);
                            commInfo.SubProtocol = INIHelper.Read(key2, "子协议号", "-1", fileConfigPath);
                            commInfo.AcquType = INIHelper.Read(key2, "采集类型", "-1", fileConfigPath);
                            commInfo.IsStart = true;
                            commInfo.MoudleAddress = GetString(MoudleAddress, commInfo.MoudleNumber);
                            commInfo.MoudleType = GetString(MoudleType, commInfo.MoudleNumber);
                            //根据模块类型判断是什么模块
                            string TypeName;
                            string[] types = commInfo.MoudleType.Split(',');
                            if (ModuleNamePairs.ContainsKey(types[0]))
                            {
                                if (ModuleNamePairs.TryGetValue(types[0], out TypeName))
                                {
                                    commInfo.MoudleName = TypeName;
                                }
                            }
                            //根据模块名称判断是否要读取道岔电流模块
                            if (commInfo.MoudleName.Contains("道岔电流模块"))
                            {
                                commInfo.DCInfos = new List<string>();
                                int num = int.Parse(commInfo.MoudleNumber);
                                for (int k = 1; k < num + 1; k++)
                                {
                                    string line = INIHelper.Read(key2, k.ToString(), "-1", fileConfigPath);
                                    commInfo.DCInfos.Add(line);
                                }

                            }

                            frankCFGInfoEntity.CommInfoEntities.Add(commInfo);
                        }
                        
                    }
                    frankCFGInfoEntities.Add(frankCFGInfoEntity);
                }
                isRight = true;                
            }
            return isRight;
        }
        public bool ReadAnalogCanConfig(List<FrankCFGInfoEntity> frankCFGInfoEntities, ref List<CANTotalInfoEntity> cANTotalInfoEntities)
        {
            bool isRight = false;
            cANTotalInfoEntities.Clear();
            //得到CAN地址
            foreach (FrankCFGInfoEntity frankCFGInfos in frankCFGInfoEntities)
            {
                foreach (CommInfoEntity CommInfos in frankCFGInfos.CommInfoEntities)
                {
                    if (CommInfos.IsStart && CommInfos.MoudleName.Equals("CAN透传模块"))
                    {
                        
                        if (int.Parse(CommInfos.MoudleNumber) >= 1)
                        {
                            string[] canAddresses = CommInfos.MoudleAddress.Split(',');
                            foreach (string canAddress in canAddresses)
                            {
                                if (canAddress != "")
                                {
                                    CANTotalInfoEntity cANTotalInfoEntity = new CANTotalInfoEntity();
                                    cANTotalInfoEntity.CANAddress = canAddress;
                                    cANTotalInfoEntity.Title = "CAN地址" + canAddress;
                                    cANTotalInfoEntity.CommIP = frankCFGInfos.CommIP;
                                    cANTotalInfoEntity.CommPort = frankCFGInfos.CANPort;
                                    cANTotalInfoEntities.Add(cANTotalInfoEntity);
                                }
                                
                            }
                        }
                        
                        
                    }
                }
            }
            if (cANTotalInfoEntities.Count > 0)
            {
                
                ReadAnalogConfig();
            }
            //读analog.ini//判断是否存在配置文件
            string fileConfigPath = GlobalVari.CFGPath + "\\analog.ini";
            if (File.Exists(fileConfigPath))
            {
                string number = INIHelper.Read("CAN通信配置", "总路数", "-1", fileConfigPath);
                for (int i = 0; i < int.Parse(number); i++)
                {
                    string canAddr = INIHelper.Read("虚拟分机" + (i + 1).ToString(), "通信板CAN地址", "-1", fileConfigPath);
                    foreach (CANTotalInfoEntity item in cANTotalInfoEntities)
                    {
                        if (item.CANAddress == canAddr)
                        {
                            string canId = INIHelper.Read("虚拟分机" + (i + 1).ToString(), "虚拟分机号", "-1", fileConfigPath);
                            item.MoudleId = canId;
                            //得到对应模拟量名称列表
                            List<string> analogNames = new List<string>();
                            if (AnalogkeyValuePairs.TryGetValue(canId, out analogNames))
                            {
                                foreach (var analogName in analogNames)
                                {
                                    CANInfoEntity cANInfoEntity = new CANInfoEntity();
                                    cANInfoEntity.MoudleId = canId;
                                    cANInfoEntity.MoudleName = analogName;
                                    item.MoudleNameList.Add(cANInfoEntity);
                                }
                                
                            }                           
                            
                        }
                    }
                    isRight = true;
                }
            }
            return isRight;
        }
        private bool ReadAnalogConfig_()
        {
            bool isRight = false;
            string parentPath = Directory.GetParent(GlobalVari.CFGPath)?.FullName;
            GetInit10Config getInit10Config = new GetInit10Config();
            if (getInit10Config.ReadAnalog(parentPath, Path.GetFileName(GlobalVari.CFGPath)))
            {
                foreach (var item in getInit10Config.AnalogEntMap)
                {

                }
                
                
            }
            
            return isRight;
        }
        private bool ReadAnalogConfig()
        {
            bool isRight = false;            
            AnalogkeyValuePairs.Clear();
            //判断是否存在配置文件
            string fileConfigPath = GlobalVari.CFGPath + "\\analog.ini";
            if (File.Exists(fileConfigPath))
            {
                string number = INIHelper.Read("模拟量项目", "子项数目", "-1", fileConfigPath);
                for (int i = 0; i < int.Parse(number); i++)
                {
                    string childNumStr = INIHelper.Read("子项" + (i + 1).ToString(), "总路数", "-1", fileConfigPath);
                    if (childNumStr.Contains(";"))
                    {
                        string[] childNumStrs = childNumStr.Split(';');
                        childNumStr = childNumStrs[0];
                    }
                    int chirdNum = 0;
                    if (Regex.IsMatch(childNumStr, "[0-9]+"))
                    {
                        chirdNum = int.Parse(childNumStr);
                    }
                    for (int j = 0; j < chirdNum; j++)
                    {
                        string analogStr = INIHelper.Read("子项" + (i + 1).ToString(), (j + 1).ToString(), "-1", fileConfigPath);
                        analogStr = analogStr.Replace(" ", "").Replace("\t", "");
                        string[] analogStrs = analogStr.Split(',');
                        string key = analogStrs[10].Trim();
                        if (AnalogkeyValuePairs.TryGetValue(key, out List<string> analogKeyValue))
                        {
                            analogKeyValue.Add(analogStr);
                        }
                        else
                        {
                            List<string> analogKeyValueTemp = new List<string>();
                            AnalogkeyValuePairs.Add(key, analogKeyValueTemp);
                            analogKeyValueTemp.Add(analogStr);
                        }

                    }
                    isRight = true;
                }
            }

            return isRight;
        }

        public bool ConfigDCCurveTool(List<FrankCFGInfoEntity> frankCFGInfoEntities, ref List<SimuAppInfo> simuAppInfos)
        {
            bool isRight = false;
            simuAppInfos.Clear();
            simuAppInfos = new List<SimuAppInfo>();
            //考虑多个道岔电流模块的情况
            foreach (FrankCFGInfoEntity frankCFGInfos in frankCFGInfoEntities)
            {
                foreach (CommInfoEntity CommInfos in frankCFGInfos.CommInfoEntities)
                {
                    if (CommInfos.IsStart && CommInfos.MoudleName.Contains("道岔电流模块"))
                    {
                        //把模拟工具拷贝到指定目录下
                        string sourcePath = Path.Combine(SourceSimuToolsPath, @"监测自采集\维博道岔电流曲线\G-道岔电流曲线_V1_0_0_0");
                        string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourcePath));
                        CopyDirectory(sourcePath, targetSimuToolPath);
                        //根据分机号重命名模拟工具文件夹
                        string targetSimuToolPathNew = targetSimuToolPath + "-" + CommInfos.MoudleId;
                        if (!Directory.Exists(targetSimuToolPathNew))
                        {
                            Directory.Move(targetSimuToolPath, targetSimuToolPathNew);
                        }
                        string ToolConfigPath = targetSimuToolPathNew + @"\cfg\";
                        string ToolConfigUnderPath = targetSimuToolPathNew + @"\cfg\" + dbm;
                        //拷贝和修改FrankCFG.ini
                        CopySpecificFile(GlobalVari.CFGPath, ToolConfigUnderPath, "FrankCFG.ini");
                        INIHelper.Write("通信板1端口1", "波特率", CommInfos.BaudRate, ToolConfigUnderPath + @"\FrankCFG.ini");
                        INIHelper.Write("通信板1端口1", "采集类型", CommInfos.AcquType, ToolConfigUnderPath + @"\FrankCFG.ini");
                        INIHelper.Write("通信板1端口1", "模块数量", CommInfos.MoudleNumber, ToolConfigUnderPath + @"\FrankCFG.ini");
                        INIHelper.Write("通信板1端口1", "模块地址", CommInfos.MoudleAddress, ToolConfigUnderPath + @"\FrankCFG.ini");
                        INIHelper.Write("通信板1端口1", "模块类型", CommInfos.MoudleType, ToolConfigUnderPath + @"\FrankCFG.ini");
                        INIHelper.Write("通信板1端口1", "分机号", CommInfos.MoudleId, ToolConfigUnderPath + @"\FrankCFG.ini");                        
                        INIHelper.Write("通信板1端口1", "主协议号", CommInfos.MainProtocol, ToolConfigUnderPath + @"\FrankCFG.ini");
                        INIHelper.Write("通信板1端口1", "子协议号", CommInfos.SubProtocol, ToolConfigUnderPath + @"\FrankCFG.ini");
                        INIHelper.Write("通信板1端口1", "辅助配置库信息", "1", ToolConfigUnderPath + @"\FrankCFG.ini");
                        for (int i = 0; i < CommInfos.DCInfos.Count(); i++)
                        {
                            INIHelper.Write("通信板1端口1", (i + 1).ToString(), CommInfos.DCInfos[i], ToolConfigUnderPath + @"\FrankCFG.ini");
                        }
                        //修改SysCfg.INI
                        INIHelper.Write("道岔", "站名", dbm, ToolConfigPath + @"\SYSCFG.ini");
                        INIHelper.Write("道岔", "服务器IP", LocalIP, ToolConfigPath + @"\SYSCFG.ini");
                        INIHelper.Write("道岔", "服务器端口", ScriptServerPort, ToolConfigPath + @"\SYSCFG.ini");
                        INIHelper.Write("串口1", "端口号", CommInfos.SimuToolPortNumber, ToolConfigPath + @"\SYSCFG.ini");
                        INIHelper.Write("串口1", "波特率", CommInfos.BaudRate, ToolConfigPath + @"\SYSCFG.ini");
                        INIHelper.Write("串口1", "对应采集板", "通信板1端口1", ToolConfigPath + @"\SYSCFG.ini");

                        //得到模拟工具名称和路径
                        //根据分机号重命名模拟工具文件
                        string toolName = "VWayside_D" + "-" + CommInfos.MoudleId;
                        string oldPath = Path.Combine(targetSimuToolPathNew, @"VWayside_D.exe");
                        string newPath = Path.Combine(targetSimuToolPathNew, toolName + @".exe");
                        if (!File.Exists(newPath))
                        {
                            Directory.Move(oldPath, newPath);
                        }
                        SimuAppInfo simuAppInfo = new SimuAppInfo(toolName, Path.Combine(targetSimuToolPathNew, toolName + @".exe"));
                        simuAppInfos.Add(simuAppInfo);

                        isRight = true;
                    }
                }
            }

            return isRight;
        }
        public bool ConfigWDWTool(List<FrankCFGInfoEntity> frankCFGInfoEntities, ref List<SimuAppInfo> simuAppInfos)
        {
            bool isRight = false;
            simuAppInfos.Clear();
            simuAppInfos = new List<SimuAppInfo>();
            
            foreach (FrankCFGInfoEntity frankCFGInfos in frankCFGInfoEntities)
            {
                foreach (CommInfoEntity CommInfos in frankCFGInfos.CommInfoEntities)
                {
                    if (CommInfos.IsStart && CommInfos.MoudleType.Contains("33"))
                    {
                        //把模拟工具拷贝到指定目录下
                        string sourcePath = Path.Combine(SourceSimuToolsPath, @"监测自采集\外电网\E-外电网\E-外电网 - V1_0_0_5");
                        string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourcePath));
                        CopyDirectory(sourcePath, targetSimuToolPath);
                        //根据分机号重命名模拟工具文件夹
                        string targetSimuToolPathNew = targetSimuToolPath + "-" + CommInfos.MoudleId;
                        if (!Directory.Exists(targetSimuToolPathNew))
                        {
                            Directory.Move(targetSimuToolPath, targetSimuToolPathNew);
                        }
                        string ToolConfigPath = targetSimuToolPathNew + @"\cfg\通信配置.ini";
                        //修改 通信配置.ini
                        INIHelper.Write("外电网通信", "端口号", CommInfos.SimuToolPortNumber, ToolConfigPath);
                        INIHelper.Write("外电网通信", "服务器IP地址", LocalIP, ToolConfigPath);
                        INIHelper.Write("外电网通信", "服务器端口", ScriptServerPort, ToolConfigPath);

                        //得到模拟工具名称和路径
                        //根据分机号重命名模拟工具文件
                        string toolName = "VPower_D" + "-" + CommInfos.MoudleId;
                        string oldPath = Path.Combine(targetSimuToolPathNew, @"VPower_D.exe");
                        string newPath = Path.Combine(targetSimuToolPathNew, toolName + @".exe");
                        if (!File.Exists(newPath))
                        {
                            Directory.Move(oldPath, newPath);
                        }
                        SimuAppInfo simuAppInfo = new SimuAppInfo(toolName, Path.Combine(targetSimuToolPathNew, toolName + @".exe"));
                        simuAppInfos.Add(simuAppInfo);
                        
                        isRight = true;
                    }
                }
            }
            
            return isRight;
        }

        public bool ConfigModbusTool(List<FrankCFGInfoEntity> frankCFGInfoEntities, ref SimuAppInfo simuAppInfo)
        {
            bool isRight = false;
            //把模拟工具拷贝到指定目录下
            string sourcePath = Path.Combine(SourceSimuToolsPath, @"监测自采集\Modbus模拟工具\6-ModbusModule-V1_0_0_19");
            string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourcePath));
            CopyDirectory(sourcePath, targetSimuToolPath);

            //1.拷贝监测配置库analog.ini和Digit.ini
            string ToolConfigPath = targetSimuToolPath + @"\cfg\";
            string ToolConfigUnderPath = targetSimuToolPath + @"\cfg\" + dbm;            
            CopySpecificFile(GlobalVari.CFGPath, ToolConfigUnderPath, "analog.ini");
            CopySpecificFile(GlobalVari.CFGPath, ToolConfigUnderPath, "Digit.ini");
            //2.修改 SYSCFG.ini
            INIHelper.Write("本机", "电报码", dbm, ToolConfigPath + @"\SYSCFG.ini");
            //3.配置config.ini
            string configFilePath = targetSimuToolPath + @"\config.ini";
            if (WriteConfigFile(frankCFGInfoEntities, configFilePath))
            {
                //得到模拟工具名称和路径
                simuAppInfo = new SimuAppInfo("ModbusModule", Path.Combine(targetSimuToolPath, @"ModbusModule.exe"));
                isRight = true;
            }            
            return isRight;
        }
        private bool WriteConfigFile(List<FrankCFGInfoEntity> frankCFGInfoEntities, string configFilePath)
        {
            bool isRight = false;
            if (File.Exists(configFilePath))
            {
                ////文件存在，则重命名旧文件后，再写入
                //string newFilePath = configFilePath.Replace(".ini", "-" + UnixTime.GetTimeStampTen() + ".ini");
                //File.Copy(configFilePath, newFilePath);
                File.Delete(configFilePath);
            }
            // 获取当前系统的默认ANSI编码
            Encoding ansiEncoding = Encoding.Default;
            // 使用ANSI编码创建并写入文件
            using (FileStream fs = new FileStream(configFilePath, FileMode.Create, FileAccess.Write))
            using (StreamWriter sw = new StreamWriter(fs, ansiEncoding))
            //using (StreamWriter sw = File.CreateText(configFilePath))
            {
                sw.WriteLine($"[{"本机"}]");
                sw.WriteLine($"{"服务器IP地址"}={LocalIP}");
                sw.WriteLine($"{"服务器端口号"}={"6789"}");

                //得到需要配置的列表
                List<CommInfoEntity> commList = new List<CommInfoEntity>();
                foreach (FrankCFGInfoEntity frankCFGInfos in frankCFGInfoEntities)
                {
                    foreach (CommInfoEntity CommInfos in frankCFGInfos.CommInfoEntities)
                    {
                        if (CommInfos.MoudleType.Contains("31") || CommInfos.MoudleType.Contains("32") || CommInfos.MoudleType.Contains("33") || CommInfos.MoudleType.Contains("34"))
                        {                            
                        }
                        else
                        {
                            commList.Add(CommInfos);
                        }
                    }
                }
                sw.WriteLine($"[{"自采类型配置"}]");
                sw.WriteLine($"{"模块数量"}={commList.Count().ToString()}");
                int num = 0;
                foreach (CommInfoEntity commInfo in commList)
                {
                    if (commInfo.IsStart)
                    {
                        num++;
                        string section = "自采类型" + num.ToString() + "配置";
                        sw.WriteLine($"[{section}]");
                        sw.WriteLine($"{"模块名称"}={commInfo.MoudleName + num.ToString()}");
                        sw.WriteLine($"{"串口号"}={commInfo.SimuToolPortNumber}");
                        sw.WriteLine($"{"波特率"}={commInfo.BaudRate}");
                        sw.WriteLine($"{"数据位"}={"8"}");
                        sw.WriteLine($"{"模块数量"}={commInfo.MoudleNumber}");
                        sw.WriteLine($"{"模块地址"}={commInfo.MoudleAddress}");
                        sw.WriteLine($"{"模块类型"}={commInfo.MoudleType}");
                        sw.WriteLine($"{"分机号"}={commInfo.MoudleId}");
                    }
                    
                }
                isRight = true;
            }
            return isRight;
        }

        public bool ConfigGYBDCTool(List<CANTotalInfoEntity> CANTotalInfos, ref List<SimuAppInfo> simuAppInfos)
        {
            bool isRight = false;
            simuAppInfos.Clear();
            Dictionary<string, List<GYBDCSectionAndAddress>> keyValuePairs = new Dictionary<string, List<GYBDCSectionAndAddress>>();
            foreach (CANTotalInfoEntity CANTotalInfo in CANTotalInfos)
            {
                if (CANTotalInfo.ToolTypeName == ToolTypeNames.type_GYBDC)
                {
                    string sectionName = "";
                    if (CANTotalInfo.MoudleNameList != null && CANTotalInfo.MoudleNameList.Count > 0)
                    {
                        string[] analogs = CANTotalInfo.MoudleNameList[0].MoudleName.Split(',');
                        string analogName = analogs[0].Trim();
                        if (analogName.Contains("_"))
                        {
                            string[] sectionNames = analogName.Split('_');
                            sectionName = sectionNames[0].Trim();
                        }
                    }
                    if (keyValuePairs.TryGetValue(CANTotalInfo.CommIP, out List<GYBDCSectionAndAddress> SectionAndAddrList))
                    {                       
                        GYBDCSectionAndAddress gYBDCSectionAndAddress = new GYBDCSectionAndAddress();
                        gYBDCSectionAndAddress.Address = CANTotalInfo.CANAddress;
                        gYBDCSectionAndAddress.Name = sectionName;
                        gYBDCSectionAndAddress.Port = CANTotalInfo.CommPort;
                        SectionAndAddrList.Add(gYBDCSectionAndAddress);
                    }
                    else
                    {
                        List<GYBDCSectionAndAddress> SectionAndAddrListTemp = new List<GYBDCSectionAndAddress>();
                        keyValuePairs.Add(CANTotalInfo.CommIP, SectionAndAddrListTemp);
                        GYBDCSectionAndAddress gYBDCSectionAndAddress = new GYBDCSectionAndAddress();
                        gYBDCSectionAndAddress.Address = CANTotalInfo.CANAddress;
                        gYBDCSectionAndAddress.Name = sectionName;
                        gYBDCSectionAndAddress.Port = CANTotalInfo.CommPort;
                        SectionAndAddrListTemp.Add(gYBDCSectionAndAddress);
                    }
                    
                }
            }
            if (keyValuePairs.Count > 0)
            {
                string commPort = "";
                foreach (var item in keyValuePairs)
                {
                    if (item.Value != null && item.Value.Count > 0)
                    {
                        commPort = item.Value[0].Port;
                    }
                    //把模拟工具拷贝到指定目录下                    
                    string sourcePath = Path.Combine(SourceSimuToolsPath, @"监测自采集\高压不对称\通用CAN接口高压不对称\通用CAN接口高压不对称模拟工具_V0_0_0_2");
                    string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourcePath));
                    CopyDirectory(sourcePath, targetSimuToolPath);
                    //根据ip重命名模拟工具文件夹
                    string[] ipStrArr = item.Key.Split('.');
                    string ipStr = ipStrArr[3].Trim();
                    string targetSimuToolPathNew = targetSimuToolPath + "-" + ipStr;
                    if (!Directory.Exists(targetSimuToolPathNew))
                    {
                        Directory.Move(targetSimuToolPath, targetSimuToolPathNew);
                    }                    
                    string ToolConfigPath = targetSimuToolPathNew + @"\cfg\";
                    string ToolConfigUnderPath = targetSimuToolPathNew + @"\cfg\" + dbm;
                    string ModuleConfigPath = ToolConfigUnderPath + @"\ModuleConfigs.xml";
                    string SysCfgPath = targetSimuToolPathNew + @"\cfg\SysCfg.ini";
                    //修改 SysCfg.ini                    
                    INIHelper.Write("本机", "站名", dbm, SysCfgPath);
                    INIHelper.Write("本机", "服务器IP", LocalIP, SysCfgPath);
                    INIHelper.Write("本机", "服务器port", ScriptServerPort, SysCfgPath);
                    INIHelper.Write("接口", "接口类型", "3", SysCfgPath);
                    //拷贝监测配置库GD.ini
                    CopySpecificFile(GlobalVari.CFGPath, ToolConfigUnderPath, "GD.ini");
                    //生成ModuleConfigs.xml
                    WriteTableColumnToXml_GYBDC(item.Value, ModuleConfigPath);

                    //配置WBTG306JD_SimulationTool.exe.config
                    string configFilePath = targetSimuToolPathNew + @"\WBTG306JD_SimulationTool.exe.config";
                    ModifyConfig(configFilePath, "UDPLocalIP", "192.168.1.22");
                    ModifyConfig(configFilePath, "UDPLocalPort", commPort);//模拟器通讯端口号
                    ModifyConfig(configFilePath, "UDPRemoteIP", "192.168.1.22");
                    ModifyConfig(configFilePath, "UDPRemotePort", "56867");

                    //得到模拟工具名称和路径
                    //根据分机号重命名模拟工具文件
                    //string toolName = "WBTG306JD_SimulationTool" + "-" + ipStr;
                    string toolName = "WBTG306JD_SimulationTool";
                    string oldPath = Path.Combine(targetSimuToolPathNew, @"WBTG306JD_SimulationTool.exe");
                    string newPath = Path.Combine(targetSimuToolPathNew, toolName + @".exe");
                    if (!File.Exists(newPath))
                    {
                        Directory.Move(oldPath, newPath);
                    }
                    SimuAppInfo simuAppInfo = new SimuAppInfo(toolName, Path.Combine(targetSimuToolPathNew, toolName + @".exe"));
                    simuAppInfos.Add(simuAppInfo);

                    isRight = true;
                }
            }

            return isRight;
        }
        private bool WriteTableColumnToXml_GYBDC(List<GYBDCSectionAndAddress> gYBDCSectionAndAddressList, string filePath)
        {
            bool isRight = false;  
            try
            {
                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                var doc = new XmlDocument();
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);
                XmlElement root = doc.CreateElement("ModuleConfigs");
                doc.AppendChild(root);
                for (int i = 0; i < gYBDCSectionAndAddressList.Count; i++)                
                {
                    //写入端口和绑定名称的键值对
                    XmlElement nodeColumn = doc.CreateElement("Moudle");
                    //创建列名,绑定名称
                    nodeColumn.SetAttribute("Id", (i + 1).ToString());
                    nodeColumn.SetAttribute("Name", gYBDCSectionAndAddressList[i].Name);
                    nodeColumn.SetAttribute("Address", gYBDCSectionAndAddressList[i].Address);
                    //加入node
                    root.AppendChild(nodeColumn);
                }
                doc.Save(filePath);

                isRight = true;
            }
            catch (Exception e)
            {
            }
            return isRight;
        }

        public bool ConfigJYLLTool(List<CANTotalInfoEntity> CANTotalInfos, ref SimuAppInfo simuAppInfo)
        {
            bool isRight = false;
            bool isExist = false;
            List<string> dljyList = new List<string>();
            List<string> dyllList = new List<string>();
            string commPort = "";
            foreach (CANTotalInfoEntity CANTotalInfo in CANTotalInfos)
            {
                if (CANTotalInfo.ToolTypeName == ToolTypeNames.type_DLJY || CANTotalInfo.ToolTypeName == ToolTypeNames.type_DYLL)
                {
                    isExist = true;
                    commPort = CANTotalInfo.CommPort;
                }
                if (CANTotalInfo.ToolTypeName == ToolTypeNames.type_DLJY)
                {
                    foreach (var item in CANTotalInfo.MoudleNameList)
                    {
                        string name = item.MoudleName;
                        dljyList.Add(name);
                    }                    
                }
                if (CANTotalInfo.ToolTypeName == ToolTypeNames.type_DYLL)
                {
                    foreach (var item in CANTotalInfo.MoudleNameList)
                    {
                        string name = item.MoudleName;
                        dyllList.Add(name);
                    }
                }
            }
            if (isExist)
            {
                //把模拟工具拷贝到指定目录下
                string sourcePath = Path.Combine(SourceSimuToolsPath, @"监测自采集\绝缘漏流\新绝缘漏流\新绝缘漏流模拟工具V0_0_0_7");
                string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourcePath));
                CopyDirectory(sourcePath, targetSimuToolPath);

                //1.修改配置库SysCfg.ini、JYCfg.ini和LLCfg.ini
                string ToolConfigPath = targetSimuToolPath + @"\cfg\";
                INIHelper.Write("本机", "服务器IP", LocalIP, ToolConfigPath + @"\SysCfg.ini");
                INIHelper.Write("本机", "服务器port", ScriptServerPort, ToolConfigPath + @"\SysCfg.ini");
                INIHelper.Write("接口", "接口类型", "3", ToolConfigPath + @"\SysCfg.ini");
                if (dljyList != null && dljyList.Count > 0)
                {
                    INIHelper.Write("绝缘", "总路数", dljyList.Count.ToString(), ToolConfigPath + @"\JYCfg.ini");
                    for (int i = 1; i <= dljyList.Count; i++)
                    {
                        INIHelper.Write("绝缘", i.ToString(), dljyList[i - 1], ToolConfigPath + @"\JYCfg.ini");
                    }
                }
                if (dyllList != null && dyllList.Count > 0)
                {
                    INIHelper.Write("漏流", "总路数", dyllList.Count.ToString(), ToolConfigPath + @"\LLCfg.ini");
                    for (int i = 1; i <= dyllList.Count; i++)
                    {
                        INIHelper.Write("漏流", i.ToString(), dyllList[i - 1], ToolConfigPath + @"\LLCfg.ini");
                    }
                }

                //2.修改NewJYLLTool.exe.config
                string configFilePath = targetSimuToolPath + @"\NewJYLLTool.exe.config";
                ModifyConfig(configFilePath, "UDPLocalIP", "192.168.1.22");
                ModifyConfig(configFilePath, "UDPLocalPort", commPort);//模拟器通讯端口号
                ModifyConfig(configFilePath, "UDPRemoteIP", "192.168.1.22");
                ModifyConfig(configFilePath, "UDPRemotePort", "56867");
                //得到模拟工具名称和路径
                simuAppInfo = new SimuAppInfo("NewJYLLTool", Path.Combine(targetSimuToolPath, @"NewJYLLTool.exe"));
                isRight = true;
            }
            return isRight;
        }
        private void ModifyConfig(string configFilePath, string keyValue, string newValue)
        {
            // 加载配置文件
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(configFilePath);

            // 找到 connectionStrings 节点
            XmlNode connectionNode = xmlDoc.SelectSingleNode("/configuration/connectionStrings");

            // 遍历 appSettings 中的 add 节点，寻找与 key 匹配的节点
            foreach (XmlNode node in connectionNode.ChildNodes)
            {
                if (node.Name == "add")
                {
                    XmlAttribute keyAttr = node.Attributes["name"];
                    if (keyAttr != null && keyAttr.Value == keyValue)
                    {
                        // 找到了匹配的节点，修改 value 属性
                        XmlAttribute valueAttr = node.Attributes["connectionString"];
                        if (valueAttr != null)
                        {
                            valueAttr.Value = newValue;
                        }
                        else
                        {
                            throw new Exception("Value attribute not found.");
                        }
                        break;
                    }
                }
            }

            // 保存修改后的配置文件
            xmlDoc.Save(configFilePath);
        }

        public bool ConfigCommBoard_CAN(List<CANTotalInfoEntity> CANTotalInfos)
        {
            bool isRight = false;
            
            //把虚拟通信版工具拷贝到指定目录下
            string sourceCommBoardPath = Path.Combine(SourceSimuToolsPath, @"监测自采集\虚拟通信板V2\虚拟通信板V2_0_0_20");
            string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourceCommBoardPath));
            // 如果目标目录不存在，则把虚拟通信版工具拷贝到指定目录下
            if (!Directory.Exists(targetSimuToolPath))
            {
                CopyDirectory(sourceCommBoardPath, targetSimuToolPath);
            }
            else
            {
                //修改配置UDPCANResource.xml
                string xmlFilePath = targetSimuToolPath + @"\cfg\UDPCANResource.xml";
                if (WriteTableColumnToXml_CAN(CANTotalInfos, xmlFilePath))
                {
                    isRight = true;
                }
            }
            return isRight;
        }
        private bool WriteTableColumnToXml_CAN(List<CANTotalInfoEntity> CANTotalInfoEntities, string filePath)
        {
            bool isRight = false;
            Dictionary<string, List<CANTotalInfoEntity>> keyValuePairs = new Dictionary<string, List<CANTotalInfoEntity>>();
            foreach (CANTotalInfoEntity canTotalInfoEntity in CANTotalInfoEntities)
            {
                if (keyValuePairs.TryGetValue(canTotalInfoEntity.CommIP, out List<CANTotalInfoEntity> KeyValues))
                {
                    KeyValues.Add(canTotalInfoEntity);
                }
                else
                {
                    List<CANTotalInfoEntity> KeyValuestTemp = new List<CANTotalInfoEntity>();
                    keyValuePairs.Add(canTotalInfoEntity.CommIP, KeyValuestTemp);
                    KeyValuestTemp.Add(canTotalInfoEntity);
                }
            }
            
            try
            {
                if (File.Exists(filePath))
                {                   
                    File.Delete(filePath);
                }
                var doc = new XmlDocument();
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);
                XmlElement root = doc.CreateElement("UDPCANResources");
                doc.AppendChild(root);
                XmlElement node = doc.CreateElement("LocalNode");
                node.SetAttribute("IP", "192.168.1.22");
                node.SetAttribute("Port", "56867");
                root.AppendChild(node);
                XmlElement node2 = doc.CreateElement("RemoteNodes");
                root.AppendChild(node2);
                //string portIDStr = "56870";
                foreach (var keyValuePair in keyValuePairs)
                {
                    //string portID = (int.Parse(portIDStr) + 1).ToString();
                    XmlElement node3 = doc.CreateElement("Info");
                    node3.SetAttribute("MasterIP", keyValuePair.Key);
                    foreach (var CANTotalInfo in keyValuePair.Value)
                    {
                        //CANTotalInfo.CommPort = portID;
                        CreateXmlElement_CAN(doc, node3, CANTotalInfo, CANTotalInfo.CommPort);
                    }

                    node2.AppendChild(node3);
                }
                doc.Save(filePath);

                isRight = true;
            }
            catch (Exception e)
            {
            }
            return isRight;
        }
        private void CreateXmlElement_CAN(XmlDocument doc, XmlElement node, CANTotalInfoEntity CANTotalInfo, string portID)
        {
            //写入端口和绑定名称的键值对
            XmlElement nodeColumn = doc.CreateElement("Node");
            //创建列名,绑定名称
            nodeColumn.SetAttribute("IP", "192.168.1.22");            
            nodeColumn.SetAttribute("Port", portID);
            nodeColumn.SetAttribute("ID", CANTotalInfo.CANAddress);
            //加入node
            node.AppendChild(nodeColumn);
        }
        public bool ConfigCommBoard(List<FrankCFGInfoEntity> frankCFGInfoEntities,ref SimuAppInfo simuAppInfo)
        {
            bool isRight = false;
            //把虚拟通信版工具拷贝到指定目录下
            string sourceCommBoardPath = Path.Combine(SourceSimuToolsPath, @"监测自采集\虚拟通信板V2\虚拟通信板V2_0_0_20");
            string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourceCommBoardPath));
            CopyDirectory(sourceCommBoardPath, targetSimuToolPath);

            //修改配置BoardCfg.xml
            string xmlFilePath = targetSimuToolPath + @"\cfg\BoardCfg.xml";
            if (WriteTableColumnToXml(frankCFGInfoEntities, xmlFilePath))
            {
                simuAppInfo = new SimuAppInfo("TDCommBoardEmulation", Path.Combine(targetSimuToolPath, @"TDCommBoardEmulation.exe"));
                isRight = true;
            }
            return isRight;
        }
        private bool WriteTableColumnToXml(List<FrankCFGInfoEntity> MultiPortBoardkeyValuePairs, string filePath)
        {
            bool isRight = false;
            try
            {
                if (File.Exists(filePath))
                {
                    ////文件存在，则重命名旧文件后，再写入
                    //string newFilePath = filePath.Replace(".xml", "-" + UnixTime.GetTimeStampTen() + ".xml");
                    //File.Copy(filePath, newFilePath);
                    File.Delete(filePath);
                }
                var doc = new XmlDocument();
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
                doc.AppendChild(dec);
                XmlElement root = doc.CreateElement("Boards");
                doc.AppendChild(root);
                foreach (var FrankCFGInfoEntity in MultiPortBoardkeyValuePairs)
                {
                    XmlElement node = doc.CreateElement("Board");
                    node.SetAttribute("IP", FrankCFGInfoEntity.CommIP);
                    foreach (var CommInfo in FrankCFGInfoEntity.CommInfoEntities)
                    {
                        CreateXmlElement(doc, node, CommInfo);
                    }

                    root.AppendChild(node);
                }
                doc.Save(filePath);

                isRight = true;
            }
            catch (Exception e)
            {                
            }
            return isRight;
        }
        private void CreateXmlElement(XmlDocument doc, XmlElement node, CommInfoEntity comPortInfo)
        {
            //写入端口和绑定名称的键值对
            XmlElement nodeColumn = doc.CreateElement("ComPortInfo");
            //创建列名,绑定名称
            nodeColumn.SetAttribute("CommOrder", comPortInfo.PortNumber);
            string portType;
            if (comPortInfo.IsStart && comPortInfo.PortType == "4")
            {
                portType = "485";
                nodeColumn.SetAttribute("ComType", portType);
                nodeColumn.SetAttribute("ComPortName", comPortInfo.CommBoardPortNumber);
            }
            else if (comPortInfo.IsStart && comPortInfo.PortType == "5")
            {
                portType = "UDPCAN";
                nodeColumn.SetAttribute("ComType", portType);
                nodeColumn.SetAttribute("ComPortName", "");
            }
            else
            {
                portType = "";
                nodeColumn.SetAttribute("ComType", "null");
                nodeColumn.SetAttribute("ComPortName", "");
            }           
            
            //加入node
            node.AppendChild(nodeColumn);
        }

        public bool ReadZPWConfig(ref SimuAppInfo simuAppInfo)
        {
            bool isRight = false;
            //判断是否存在配置文件
            string fileConfigPath = GlobalVari.CFGPath + "\\ZPW.ini";
            if (File.Exists(fileConfigPath))
            {
                //创建副本
                CreateBackup(fileConfigPath, GlobalVari.CFGPath);
                //修改监测配置库
                INIHelper.Write("ZPW2000A通信设置", "ZPW服务器IP地址三", LocalIP, fileConfigPath);
                INIHelper.Write("ZPW2000A通信设置", "本机IP地址", LocalIP, fileConfigPath);
                //把zpw2000模拟工具拷贝到指定目录下
                string sourceZPWPath = Path.Combine(SourceSimuToolsPath, @"ZPW2000\QCR780_2_ZPW2000\ZPW2000ARJ45V3_V0_0_0_27");
                string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourceZPWPath));
                CopyDirectory(sourceZPWPath, targetSimuToolPath);
                
                string ToolConfigPath = targetSimuToolPath + @"\cfg\";
                string SysConfigPath = ToolConfigPath + @"\SysCfg.ini";
                string ToolConfigUnderPath = ToolConfigPath + dbm;
                string ZPWDataConfigPath = ToolConfigUnderPath + @"\ZPWData.ini";
                //修改SysCfg.ini
                INIHelper.Write("轨道电路ZPW2000A", "RJ45站名", dbm, SysConfigPath);
                INIHelper.Write("轨道电路ZPW2000A", "服务器IP", LocalIP, SysConfigPath);
                INIHelper.Write("轨道电路ZPW2000A", "服务器port", ScriptServerPort, SysConfigPath);
                INIHelper.Write("轨道电路ZPW2000A", "模拟类型", "2", SysConfigPath);//后续增加判断是哪种类型的区间轨道电路
                INIHelper.Write("轨道电路ZPW2000A", "通信方式", "2", SysConfigPath);
                INIHelper.Write("IPV4服务端", "本机IP", LocalIP, SysConfigPath);
                INIHelper.Write("IPV4服务端", "本机端口", "5560", SysConfigPath);
                //拷贝监测配置库YP.ini
                CopySpecificFile(GlobalVari.CFGPath, ToolConfigUnderPath, "YP.ini");
                //根据ZPW.ini生成ZPWData.ini
                CopySpecificFile(GlobalVari.CFGPath, ToolConfigUnderPath, "ZPW.ini");
                if (File.Exists(ZPWDataConfigPath))
                {
                    File.Delete(ZPWDataConfigPath);
                }
                File.Move(ToolConfigUnderPath + @"\ZPW.ini", ZPWDataConfigPath);
                
                if (WriteZPWDataFile(ZPWDataConfigPath))
                {
                    //得到模拟工具名称和路径
                    simuAppInfo = new SimuAppInfo("ZPW2000ARJ45V3", Path.Combine(targetSimuToolPath, @"ZPW2000ARJ45V3.exe"));
                    isRight = true;
                }
            }
            return isRight;
        }
        private bool WriteZPWDataFile(string configFilePath)
        {
            bool isRight = false;
            if (File.Exists(configFilePath))
            {
                INIHelper.DeleteSection("ZPW2000A通信设置", configFilePath);
                INIHelper.DeleteSection("ZPW2000A调试开关设置", configFilePath);
                INIHelper.DeleteSection("客专监测配置", configFilePath);
                INIHelper.DeleteSection("轨道区段编码信息", configFilePath);
                INIHelper.DeleteSection("开关量起始序号配置", configFilePath);

                List<string> sections = new List<string>();
                string NumStr = INIHelper.Read("客专机柜配置", "客专机柜总数目", "-1", configFilePath);
                int Num = 0;
                if (Regex.IsMatch(NumStr, "[0-9]+"))
                {
                    Num = int.Parse(NumStr);
                }
                for (int i = 0; i < Num; i++)
                {
                    string secNum = INIHelper.Read("机柜" + (i + 1).ToString(), "总路数", "-1", configFilePath);
                    for (int j = 0; j < int.Parse(secNum); j++)
                    {
                        string secStr = INIHelper.Read("机柜" + (i + 1).ToString(), (j + 1).ToString(), "-1", configFilePath);
                        string[] secStrs = secStr.Split(',');
                        if (secStrs[0].Trim().ToUpper() != "DUMMY")
                        {
                            sections.Add(secStrs[0].Trim());
                        }                        
                    }
                }
                // 获取当前系统的默认ANSI编码
                Encoding ansiEncoding = Encoding.Default;
                using (StreamWriter sw = new StreamWriter(configFilePath, true, ansiEncoding))
                {
                    sw.WriteLine($"[{"基本信息"}]");
                    sw.WriteLine($"{"客专轨道电路移频柜数量"}={NumStr}");
                    sw.WriteLine($"{"客专通信编码ZPW-2000区段数量"}={sections.Count.ToString()}");
                    sw.WriteLine($"{"ZPW-2000分机数量"}={"1"}");
                    sw.WriteLine($"{"既有继电编码ZPW-2000区段数量"}={"0"}");
                    sw.WriteLine($"{"站内一体化区段数量"}={"0"}");
                    sw.WriteLine($"{"脉冲叠加轨道电路区段数量"}={"0"}");
                    sw.WriteLine($"{"数据版本"}={"1.2.3.4"}");

                    sw.WriteLine($"[{"客专通信编码ZPW-2000区段"}]");
                    for (int i = 0; i < sections.Count; i++)
                    {
                        sw.WriteLine($"{(i + 1).ToString()}={sections[i]}");
                    }
                    sw.WriteLine($"[{"既有继电编码ZPW-2000区段"}]");
                    sw.WriteLine($"[{"站内一体化区段"}]");
                    sw.WriteLine($"[{"脉冲叠加轨道电路区段"}]");
                    isRight = true;
                }
            }            
            return isRight;
        }
        public bool ReadDYPConfig(ref List<SimuAppInfo> simuAppInfos)
        {
            simuAppInfos.Clear();
            //SerCom.ini中电源屏端口从COM13开始
            int portNum = 13;
            bool isRight = false;
            //判断是否存在配置文件
            if (cfgType == CfgType.CSM_TD_10)
            {
                string fileConfigPath = GlobalVari.CFGPath + "\\SerCom.ini";
                if (File.Exists(fileConfigPath))
                {
                    string dypNumStr = INIHelper.Read("华为智能电源屏通信设置", "串口数目", "-1", fileConfigPath);
                    if (int.Parse(dypNumStr) >= 1)
                    {
                        //创建副本
                        CreateBackup(fileConfigPath, GlobalVari.CFGPath);
                        for (int i = 0; i < int.Parse(dypNumStr); i++)
                        {
                            DYPInfoEntity dYPInfoEntity = new DYPInfoEntity();
                            dYPInfoEntity.DYPSerialPort = "COM" + portNum.ToString();
                            dYPInfoEntity.DYPToolSerialPort = "COM" + (portNum + 1).ToString();
                            portNum += 2;
                            //修改监测配置库：                        
                            INIHelper.Write("华为智能电源屏通信口" + (i + 1).ToString(), "名称", dYPInfoEntity.DYPSerialPort, fileConfigPath);
                            //读取分机号
                            dYPInfoEntity.DYPFenJiID = INIHelper.Read("华为智能电源屏通信口" + (i + 1).ToString(), "对应的分机号", "-1", fileConfigPath);
                            //把电源屏模拟工具拷贝到指定目录下
                            string sourceDYPPath = Path.Combine(SourceSimuToolsPath, @"电源屏\通用电源屏\C-电源屏");
                            string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourceDYPPath));
                            CopyDirectory(sourceDYPPath, targetSimuToolPath);

                            //根据分机号重命名模拟工具文件夹
                            string targetSimuToolPathNew = targetSimuToolPath + "-" + dYPInfoEntity.DYPFenJiID;
                            if (!Directory.Exists(targetSimuToolPathNew))
                            {
                                Directory.Move(targetSimuToolPath, targetSimuToolPathNew);
                            }
                            //拷贝监测配置库并修改端口号
                            string ToolConfigPath = targetSimuToolPathNew + @"\cfg\";
                            string ToolConfigUnderPath = targetSimuToolPathNew + @"\cfg\" + dbm;
                            string SerComConfigPath = ToolConfigUnderPath + @"\SerCom.ini";
                            CopyDirectory(GlobalVari.CFGPath, ToolConfigUnderPath);
                            for (int j = 0; j < i; j++)
                            {
                                INIHelper.DeleteSection("华为智能电源屏通信口" + (j + 1).ToString(), SerComConfigPath);
                            }
                            INIHelper.Write("华为智能电源屏通信设置", "串口数目", "1", SerComConfigPath);
                            INIHelper.Write("华为智能电源屏通信口" + (i + 1).ToString(), "名称", dYPInfoEntity.DYPToolSerialPort, SerComConfigPath);
                            if (i > 0)//把当前字段改成"华为智能电源屏通信口1"
                            {
                                List<string> keyList = ReadIni.ReadSectionAllLine(SerComConfigPath, "华为智能电源屏通信口" + (i + 1).ToString(), "-1");
                                foreach (string key in keyList)
                                {
                                    if (key.Contains("="))
                                    {
                                        string[] keyArr = key.Split('=');
                                        INIHelper.Write("华为智能电源屏通信口1", keyArr[0], keyArr[1], SerComConfigPath);
                                    }
                                }
                            }
                            //修改 SYSCFG.ini
                            INIHelper.Write("本机", "电报码", dbm, ToolConfigPath + @"\SYSCFG.ini");
                            INIHelper.Write("本机", "服务器IP地址", LocalIP, ToolConfigPath + @"\SYSCFG.ini");
                            INIHelper.Write("本机", "服务器端口号", ScriptServerPort, ToolConfigPath + @"\SYSCFG.ini");

                            //得到模拟工具名称和路径
                            //根据分机号重命名模拟工具文件
                            string toolName = "电源屏" + "-" + dYPInfoEntity.DYPFenJiID;
                            string oldPath = Path.Combine(targetSimuToolPathNew, @"电源屏.exe");
                            string newPath = Path.Combine(targetSimuToolPathNew, toolName + @".exe");
                            if (!File.Exists(newPath))
                            {
                                Directory.Move(oldPath, newPath);
                            }
                            SimuAppInfo simuAppInfo = new SimuAppInfo(toolName, newPath);
                            simuAppInfos.Add(simuAppInfo);

                        }
                        isRight = true;
                    }
                }
            }
            else if (cfgType == CfgType.CSM_TD_20)
            {
                string fileConfigPath = GlobalVari.CFGPath + "\\Interface.ini";
                if (File.Exists(fileConfigPath))
                {
                    //串口电源屏
                    string dypNumStr = INIHelper.Read("华为智能电源屏通信设置", "串口数目", "-1", fileConfigPath);
                    if (int.Parse(dypNumStr) >= 1)
                    {                        
                        CreateBackup(fileConfigPath, GlobalVari.CFGPath);//创建副本
                        for (int i = 0; i < int.Parse(dypNumStr); i++)
                        {
                            DYPInfoEntity dYPInfoEntity = new DYPInfoEntity();
                            dYPInfoEntity.DYPSerialPort = "COM" + portNum.ToString();
                            dYPInfoEntity.DYPToolSerialPort = "COM" + (portNum + 1).ToString();
                            portNum += 2;
                            //修改监测配置库：                        
                            INIHelper.Write("华为智能电源屏通信口" + (i + 1).ToString(), "名称", dYPInfoEntity.DYPSerialPort, fileConfigPath);
                            //读取分机号
                            dYPInfoEntity.DYPFenJiID = INIHelper.Read("华为智能电源屏通信口" + (i + 1).ToString(), "对应的分机号", "-1", fileConfigPath);
                            //把电源屏模拟工具拷贝到指定目录下
                            string sourceDYPPath = Path.Combine(SourceSimuToolsPath, @"电源屏\通用电源屏\C-电源屏");
                            string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourceDYPPath));
                            CopyDirectory(sourceDYPPath, targetSimuToolPath);
                            //根据分机号重命名模拟工具文件夹
                            string targetSimuToolPathNew = targetSimuToolPath + "-" + dYPInfoEntity.DYPFenJiID;
                            if (!Directory.Exists(targetSimuToolPathNew))
                            {
                                Directory.Move(targetSimuToolPath, targetSimuToolPathNew);
                            }
                            //拷贝监测配置库并修改端口号
                            string ToolConfigPath = targetSimuToolPathNew + @"\cfg\";
                            string ToolConfigUnderPath = targetSimuToolPathNew + @"\cfg\" + dbm;
                            string InterfaceConfigPath = ToolConfigUnderPath + @"\Interface.ini";
                            string SerComConfigPath = ToolConfigUnderPath + @"\SerCom.ini";
                            CopyDirectory(GlobalVari.CFGPath, ToolConfigUnderPath);
                            for (int j = 0; j < i; j++)
                            {
                                INIHelper.DeleteSection("华为智能电源屏通信口" + (j + 1).ToString(), SerComConfigPath);
                            }
                            INIHelper.Write("华为智能电源屏通信设置", "串口数目", "1", SerComConfigPath);
                            INIHelper.Write("华为智能电源屏通信口" + (i + 1).ToString(), "名称", dYPInfoEntity.DYPToolSerialPort, SerComConfigPath);
                            if (i > 0)//把当前字段改成"华为智能电源屏通信口1"
                            {
                                List<string> keyList = ReadIni.ReadSectionAllLine(SerComConfigPath, "华为智能电源屏通信口" + (i + 1).ToString(), "-1");
                                foreach (string key in keyList)
                                {
                                    if (key.Contains("="))
                                    {
                                        string[] keyArr = key.Split('=');
                                        INIHelper.Write("华为智能电源屏通信口1", keyArr[0], keyArr[1], SerComConfigPath);
                                    }
                                }
                            }
                            //20版增加：把文件名Interface.ini改成SerCom.ini
                            if (!File.Exists(SerComConfigPath))
                            {
                                Directory.Move(InterfaceConfigPath, SerComConfigPath);
                            }
                            //修改 SYSCFG.ini
                            INIHelper.Write("本机", "电报码", dbm, ToolConfigPath + @"\SYSCFG.ini");
                            INIHelper.Write("本机", "服务器IP地址", LocalIP, ToolConfigPath + @"\SYSCFG.ini");
                            INIHelper.Write("本机", "服务器端口号", ScriptServerPort, ToolConfigPath + @"\SYSCFG.ini");
                            //得到模拟工具名称和路径//根据分机号重命名模拟工具文件
                            string toolName = "电源屏" + "-" + dYPInfoEntity.DYPFenJiID;
                            string oldPath = Path.Combine(targetSimuToolPathNew, @"电源屏.exe");
                            string newPath = Path.Combine(targetSimuToolPathNew, toolName + @".exe");
                            if (!File.Exists(newPath))
                            {
                                Directory.Move(oldPath, newPath);
                            }
                            SimuAppInfo simuAppInfo = new SimuAppInfo(toolName, newPath);
                            simuAppInfos.Add(simuAppInfo);
                        }
                        isRight = true;
                    }
                    //网口电源屏
                    foreach (var item in InterfacekeyValuePairs)
                    {
                        //0代表网口电源屏接口类型
                        if (item.Key == "0")
                        {
                            CreateBackup(fileConfigPath, GlobalVari.CFGPath);//创建Interface.ini副本
                            InterfacekeyValuePairs.TryGetValue(item.Key, out List<string> Sections);
                            foreach (string Section in Sections)
                            {
                                //读取监测配置库：Interface.ini的信息
                                DYPInfoEntity dYPInfoEntity = new DYPInfoEntity();
                                dYPInfoEntity.DYPFenJiID = INIHelper.Read(Section, "分机号", "-1", fileConfigPath);
                                dYPInfoEntity.DYPFactoryName = INIHelper.Read(Section, "厂家名称", "-1", fileConfigPath);
                                dYPInfoEntity.DYPInterfaceFileName = INIHelper.Read(Section, "接口文件名称", "-1", fileConfigPath);
                                dYPInfoEntity.DYPPort = INIHelper.Read(Section, "端口号", "-1", fileConfigPath);
                                dYPInfoEntity.DYPIp = LocalIP;
                                //修改监测配置库：Interface.ini的ip地址
                                INIHelper.Write(Section, "IP地址", LocalIP, fileConfigPath);
                                //把电源屏模拟工具拷贝到指定目录下
                                string sourceDYPPath = Path.Combine(SourceSimuToolsPath, @"电源屏\QRC780_2_电源屏\A电源屏-网口-V1_0_0_3");
                                string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourceDYPPath));
                                CopyDirectory(sourceDYPPath, targetSimuToolPath);
                                //根据分机号重命名模拟工具文件夹
                                string targetSimuToolPathNew = targetSimuToolPath + "-" + dYPInfoEntity.DYPFenJiID;
                                if (!Directory.Exists(targetSimuToolPathNew))
                                {
                                    Directory.Move(targetSimuToolPath, targetSimuToolPathNew);
                                }
                                //拷贝监测配置库digit.ini、ZH.ini和中心屏微机监测量表.ini
                                string ToolConfigPath = targetSimuToolPathNew + @"\cfg\SYSCFG.ini";
                                string ToolConfigUnderPath = targetSimuToolPathNew + @"\cfg\" + dbm;
                                string dyp_ConfigPath = ToolConfigUnderPath + @"\dyp_config.ini";
                                CopySpecificFile(GlobalVari.CFGPath, ToolConfigUnderPath, "digit.ini");
                                CopySpecificFile(GlobalVari.CFGPath, ToolConfigUnderPath, "ZH.ini");
                                CopySpecificFile(GlobalVari.CFGPath, ToolConfigUnderPath, dYPInfoEntity.DYPInterfaceFileName);
                                //复制并修改dyp_config.ini
                                string pathTemp = targetSimuToolPathNew + @"\cfg\CS1";
                                CopySpecificFile(pathTemp, ToolConfigUnderPath, "dyp_config.ini");
                                INIHelper.Write("电源屏配置", "分机号", dYPInfoEntity.DYPFenJiID, dyp_ConfigPath);
                                INIHelper.Write("电源屏配置", "接口文件名称", dYPInfoEntity.DYPInterfaceFileName, dyp_ConfigPath);
                                INIHelper.Write("网络连接控制", "本地IP地址", LocalIP, dyp_ConfigPath);
                                INIHelper.Write("网络连接控制", "本地端口号", dYPInfoEntity.DYPPort, dyp_ConfigPath);
                                //修改 SYSCFG.ini
                                INIHelper.Write("本机", "电报码", dbm, ToolConfigPath );
                                INIHelper.Write("本机", "服务器IP地址", LocalIP, ToolConfigPath);
                                INIHelper.Write("本机", "服务器端口号", ScriptServerPort, ToolConfigPath);
                                INIHelper.Write("本机", "厂家名称", dYPInfoEntity.DYPFactoryName, ToolConfigPath);
                                //得到模拟工具名称和路径//根据分机号重命名模拟工具文件
                                string toolName = "电源屏" + "-" + dYPInfoEntity.DYPFenJiID;
                                string oldPath = Path.Combine(targetSimuToolPathNew, @"电源屏.exe");
                                string newPath = Path.Combine(targetSimuToolPathNew, toolName + @".exe");
                                if (!File.Exists(newPath))
                                {
                                    Directory.Move(oldPath, newPath);
                                }
                                SimuAppInfo simuAppInfo = new SimuAppInfo(toolName, newPath);
                                simuAppInfos.Add(simuAppInfo);
                            }
                            isRight = true;
                        }                        
                    }
                }
            }
            
            return isRight;
        }
        public bool ReadCBIConfig(ref SimuAppInfo simuAppInfo)
        {
            bool isRight = false;
            //判断是否存在配置文件
            if (cfgType == CfgType.CSM_TD_10)
            {
                string fileConfigPath = GlobalVari.CFGPath + "\\SerCom.ini";
                if (File.Exists(fileConfigPath))
                {
                    CBIInfoEntity cBIInfoEntity = new CBIInfoEntity();
                    string SerComText = File.ReadAllText(fileConfigPath, Encoding.Default);
                    //协议类型+联锁通信设置
                    foreach (var type in cBITypes)
                    {
                        if (SerComText.Contains(type + "联锁通信设置"))
                        {
                            cBIInfoEntity.CBIType = type;
                        }
                    }
                    if (cBIInfoEntity.CBIType != null)
                    {
                        //创建副本
                        CreateBackup(fileConfigPath, GlobalVari.CFGPath);

                        cBIInfoEntity.CBIFenJi = INIHelper.Read(cBIInfoEntity.CBIType + "通信口1", "开关量对应的分机号", "-1", fileConfigPath);
                        cBIInfoEntity.CBIBaudRate = INIHelper.Read(cBIInfoEntity.CBIType + "通信口1", "波特率", "-1", fileConfigPath);
                        cBIInfoEntity.CBISerialPort = "COM11";
                        //修改监测配置库：SerCom.ini中联锁端口为COM11
                        INIHelper.Write(cBIInfoEntity.CBIType + "通信口1", "名称", cBIInfoEntity.CBISerialPort, fileConfigPath);

                        //把联锁模拟工具拷贝到指定目录下
                        string sourceCBIPath = Path.Combine(SourceSimuToolsPath, @"联锁\综合A-联锁\A-联锁_V1_0_0_1");
                        string targetSimuToolPath = Path.Combine(TargetSimuToolsPath, Path.GetFileName(sourceCBIPath));
                        CopyDirectory(sourceCBIPath, targetSimuToolPath);

                        //产生联锁模拟工具配置:
                        //1.拷贝监测配置库并修改端口号
                        string CBIToolConfigPath = targetSimuToolPath + @"\cfg\";
                        string CBIToolConfigUnderPath = targetSimuToolPath + @"\cfg\" + dbm;
                        CopyDirectory(GlobalVari.CFGPath, CBIToolConfigUnderPath);
                        INIHelper.Write(cBIInfoEntity.CBIType + "通信口1", "名称", "COM12", CBIToolConfigUnderPath + @"\SerCom.ini");
                        //2.修改 SYSCFG.ini
                        INIHelper.Write("站机1", "本地电报码", dbm, CBIToolConfigPath + @"\SYSCFG.ini");
                        INIHelper.Write("站机1", "服务器IP地址", LocalIP, CBIToolConfigPath + @"\SYSCFG.ini");
                        INIHelper.Write("站机1", "服务器端口", ScriptServerPort, CBIToolConfigPath + @"\SYSCFG.ini");
                        //3.修改 通信配置.ini
                        INIHelper.Write("联锁通信", "端口号", "COM12", CBIToolConfigPath + @"\通信配置.ini");
                        INIHelper.Write("联锁通信", "波特率", cBIInfoEntity.CBIBaudRate, CBIToolConfigPath + @"\通信配置.ini");
                        INIHelper.Write("联锁通信", "分机号", cBIInfoEntity.CBIFenJi, CBIToolConfigPath + @"\通信配置.ini");
                        INIHelper.Write("联锁通信", "联锁协议类型", cBIInfoEntity.CBIType + "联锁", CBIToolConfigPath + @"\通信配置.ini");

                        //得到模拟工具名称和路径
                        simuAppInfo = new SimuAppInfo("LS_D", Path.Combine(targetSimuToolPath, @"LS_D.exe"));
                        isRight = true;
                    }
                }
            }
            else if (cfgType == CfgType.CSM_TD_20)
            {
                
            }

            return isRight;
        }
        
        //创建副本
        private void CreateBackup(string sourceFilePath, string backupFolderPath)
        {
            // 获取备份文件名，这里是在原文件名后加上当前时间戳
            string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            string destinationFilePath = Path.Combine(backupFolderPath, Path.GetFileNameWithoutExtension(sourceFilePath) + "_" + timestamp + Path.GetExtension(sourceFilePath));

            try
            {
                // 复制文件到备份目录
                File.Copy(sourceFilePath, destinationFilePath, true);
                Console.WriteLine($"文件已成功备份到：{destinationFilePath}");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"备份文件时发生错误：{ex.Message}");
            }
        }

        // 递归方法，用于复制源目录到目标目录
        private void CopyDirectory(string sourceDirectory, string targetDirectory)
        {
            // 如果目标目录不存在，则创建它
            if (!Directory.Exists(targetDirectory))
            {
                Directory.CreateDirectory(targetDirectory);
            }
            // 获取源目录中的所有文件及子目录
            string[] files = Directory.GetFiles(sourceDirectory);
            string[] directories = Directory.GetDirectories(sourceDirectory);

            // 复制文件到目标目录
            foreach (string file in files)
            {
                string fileName = Path.GetFileName(file);
                string destFile = Path.Combine(targetDirectory, fileName);
                File.Copy(file, destFile, true);
            }

            // 递归复制子目录
            foreach (string dir in directories)
            {
                string subdir = Path.Combine(targetDirectory, Path.GetFileName(dir));
                if (!Directory.Exists(subdir))
                {
                    Directory.CreateDirectory(subdir);
                }
                CopyDirectory(dir, subdir);
            }
        }

        private string GetString(string oldStr, string strNum)
        {
            string newStr = "";
            string[] parts = oldStr.Split(',');
            for (int i = 0; i < int.Parse(strNum); i++)
            {
                newStr += parts[i] + ",";
            }

            return newStr;
        }

        private void CopySpecificFile(string sourceDirPath, string destDirPath, string fileName)
        {
            if (!Directory.Exists(destDirPath))
            {
                Directory.CreateDirectory(destDirPath);
            }
            // 构建完整的源文件路径
            string sourceFilePath = Path.Combine(sourceDirPath, fileName);

            // 检查文件是否存在
            if (File.Exists(sourceFilePath))
            {
                // 如果目标目录不存在，则创建它
                Directory.CreateDirectory(destDirPath);
                // 构建目标文件路径
                string destFilePath = Path.Combine(destDirPath, fileName);
                // 复制文件到目标目录
                File.Copy(sourceFilePath, destFilePath, true); // 设置为true以覆盖已存在的文件
                Console.WriteLine($"File {fileName} copied successfully.");
            }
            else
            {
                Console.WriteLine($"File {fileName} does not exist in the source directory.");
            }
        }
    }
}
